import {createComputed, createEval, createStep, pickRW4Scope} from './ConvertItems';
import {createChildren, createType} from "./RenderRule.js"
import {RW, treeMap} from "dlsjs"

const reservedProperty = {
  '@step': function(value, params) {
    let steps = value['@step']
    return createStep(steps, params)
  },
  '@eval': function (value, params) {
    return createEval(value['@eval'], params)
  },
  '@computed': function (value, params) {
    return createComputed(value['@computed'], params)
  },
  '@json': function (value, params) {
    return JSON.parse(value['@json'])
  }
}

const reservedWord = {
  '@scope': pickRW4Scope,
  '@dataScope': pickRW4Scope
}

const reservedKey = {
  'children': createChildren,
  'type': createType
}

const reservedDeepProperty = {
  '@permLevel': function (value, params) {
    RW(value)['#/props/class/readonlyEditor'] = value['@permLevel'] === 'readonly';
    RW(value)['#/props/class/hideEditor'] = value['@permLevel'] === 'hide';
    return value
  }
}
/**
 * 可以把符合条件的字符或者对象转换为目标格式
 * @param data
 * @param params
 * @return {(function(): void)|*}
 */
export function transValue(data, params) {
  if(reservedKey.hasOwnProperty(params.key)) {
    return reservedKey[params.key](data, params)
  }
  if(Object.prototype.toString.call(data) === '[object Object]') {
    for(let key in data) {
      if(reservedProperty.hasOwnProperty(key)) {
        return reservedProperty[key](data, params)
      }else if(reservedDeepProperty.hasOwnProperty(key)) {
        return reservedDeepProperty[key](data, params)
      }
    }
  }
  if(typeof data === 'string') {
    let regexRes = /^(@[a-zA-Z0-9]+)\/(.+)/.exec(data)
    if(regexRes) {
      const [matchString, $1, $2] = regexRes;
      if(reservedWord.hasOwnProperty($1)) {
        return reservedWord[$1](data, params, $2)
      }
    }
  }
  return data
}

/**
 * 终止符判断
 * @param data
 * @param params
 * @returns {boolean}
 */
export function isTerminator(data, params) {
  if(reservedKey.hasOwnProperty(params.key)) {
    return true
  }
  if(Object.prototype.toString.call(data) === '[object Object]') {
    for(let key in data) {
      if(reservedProperty.hasOwnProperty(key) && !(data.hasOwnProperty('@canDeep') || data.hasOwnProperty('@json') || data.hasOwnProperty('@stepV2'))) {
        return true
      }else if(reservedProperty.hasOwnProperty(key) && (data.hasOwnProperty('@canDeep') || data.hasOwnProperty('@json') || data.hasOwnProperty('@stepV2'))){
        return 'deep'
      }else if(reservedDeepProperty.hasOwnProperty(key)) {
        reservedDeepProperty[key](data, params)
      }
    }
  }
  if(typeof data === 'string') {
    let regexRes = /^(@[a-zA-Z0-9]+)\/(.+)/.exec(data)
    if(regexRes) {
      const [matchString, $1, $2] = regexRes;
      if(reservedWord.hasOwnProperty($1)) {
        return true
      }
    }
  }
  return false
}
